import {EVT_PLAYER_SET_P} from "./Core/AppEvent";
import {addListener, dispatchEvent} from "./Managers/EventManager";


const {ccclass, property} = cc._decorator;


@ccclass
export default class JoyStick extends cc.Component {
    @property(cc.Node)
    dotSprite: cc.Node = null;
    
    startPoint = new cc.Vec2(0,0);

    onLoad(){
    }

    public onTouchStart(event) {
        let location = event.getLocation();
        let winSize = cc.view.getVisibleSize();
        this.node.position = new cc.Vec3(location.x - winSize.width/2, location.y - winSize.height/2, 0);
        this.startPoint = location;
    }

    public onTouchMove(event) {
        let location = event.getLocation();
        let offsetX = location.x - this.startPoint.x;
        let offsetY = location.y - this.startPoint.y;
        let contentSize = this.node.getContentSize();
        let length = location.sub(cc.v2(this.startPoint)).mag(); 
        let p = location.sub(cc.v2(this.startPoint)).normalize();
        let radius = contentSize.width/2
        if(length <= radius){
            this.dotSprite.position = new cc.Vec3(offsetX, offsetY, 0);
        }else{
            this.dotSprite.position = new cc.Vec3(radius*p.x, radius*p.y, 0);
        }
        dispatchEvent(EVT_PLAYER_SET_P, { p: p});
        // if(offsetX > radius){
        //     offsetX = radius
        // }else if(offsetX < -radius){
        //     offsetX = -radius
        // }
        // if(offsetY > radius){
        //     offsetY = radius
        // }else if(offsetY < -radius){
        //     offsetY = -radius
        // }

    }

    public onTouchEnd(event) {
        this.dotSprite.position = cc.Vec3.ZERO;
        dispatchEvent(EVT_PLAYER_SET_P, { p: cc.v3(0,0,0)});
    }

}
